<template>
  <div class="channelConfig">
    <h2 class="title">案场渠道配置</h2>
    <div class="teamConfigBtn">
      <div class="searchBox">
        <div class="caseSearch">
          <Select
            v-model="buildingId"
            placeholder="请选择案场"
            :label-in-value="true"
            @on-change="buildingIdValChange"
            style="min-width: 220px; margin-right: 10px"
          >
            <Option
              v-for="(item, index) in caseList"
              :key="index"
              :value="item.buildingId"
              :label="item.buildingAlias"
            >
            </Option>
          </Select>
          <!-- <Select
            v-model="searchChannelTypeVal"
            placeholder="请选择渠道分类"
            clearable
            @on-change="searchChange"
            style="min-width: 220px; margin-right: 10px"
          >
            <Option
              v-for="(item, index) in channelTypeData"
              :key="index"
              :value="item.id"
              :label="item.value"
            >
            </Option>
          </Select>
          <Input
            v-model="searchChannelName"
            style="min-width: 220px; margin-right: 10px"
            @on-change="searchChange"
            placeholder="请输入渠道名称"
            clearable
          />
          <Button type="primary" class="serBtn" @click="searchBtn">查询</Button>
          <Button type="primary" @click="searchReset">重置</Button> -->
        </div>
      </div>
      <Button type="primary" @click="addChannel">新增配置</Button>
    </div>

    <div class="tab">
      <Table
        ref="TableHeight"
        :max-height="onresizeHeight"
        :columns="columns"
        :data="data"
        border
      >
        <!-- <template slot-scope="{ row }" slot="channelName">
          <span class="sp1" v-for="item in row.list">{{
            item.channelName
          }}</span>
        </template>
        <template slot-scope="{ row }" slot="passagewayName">
          <span class="sp1" v-for="(item, index) in row.list">
            <em v-for="(items, index) in item.passageway" :key="index">
              {{ items.channelName
              }}{{ index == item.passageway.length - 1 ? "" : "," }}
            </em>
          </span>
        </template>
        <template slot-scope="{ row }" slot="operation">
          <div v-for="item in row.list" class="sp1">
            <span class="caoBtn" @click="disableChannel(item)">{{
              item.validate == 1 ? "禁用" : "启用"
            }}</span>
            <span class="caoBtn" @click="editChannel(item)">编辑</span>
          </div>
        </template> -->
      </Table>
    </div>

    <!-- 分页 -->
    <div class="pagePublicStyle" v-show="pageData.total > 0">
      <div class="totalCount">
        当前第 {{ pageData.current }} 页， 当前第
        {{ (pageData.current - 1) * pageData.rows + 1 }} 条到第
        {{
          pageData.current * pageData.rows > pageData.total
            ? pageData.total
            : pageData.current * pageData.rows
        }}
        条， 共 {{ pageData.total }} 条
      </div>
      <Page
        :total="pageData.total"
        :current="pageData.current"
        :page-size-opts="pageData.pageSizeOpts"
        @on-change="pageOnChangeFun"
        @on-page-size-change="pageOnPageSizeChangeFun"
        show-elevator
        show-sizer
        show-total
      />
    </div>
    <!-- 添加配置弹出框 -->
    <Modal v-model="modal" title="客户渠道" @on-cancel="modalCancel">
      <div class="modalCon">
        <span>案场：</span>
        <div class="modalConSel">
          <Input v-model="buildingAlias" disabled />
        </div>
      </div>
      <div class="modalCon">
        <span>渠道分类：</span>
        <div class="modalConSel">
          <Select
            v-model="channelTypeVal"
            placeholder="请选择渠道分类"
            :disabled="!create"
            @on-change="channelTypeChange"
          >
            <Option
              v-for="(item, index) in channelTypeData"
              :key="index"
              :value="item.id"
              :label="item.value"
            >
            </Option>
          </Select>
        </div>
      </div>
      <div class="modalCon">
        <span>渠道名称：</span>
        <div class="modalConSel">
          <RadioGroup v-model="channelNameQie" @on-change="channelNameChange">
            <Radio label="1" :disabled="kuDisabled || kuDisabled1"
              >渠道库</Radio
            >
            <Radio label="2" :disabled="kuDisabled">自定义</Radio>
          </RadioGroup>
          <div class="nameSel" v-if="channelNameQie == 1 && !kuDisabled" >
            <Select
              v-model="librarySelVal"
              placeholder="请选择渠道"
              clearable
              filterable
              @on-change="librarySelChange"
              :label-in-value="true"
              :disabled="kuDisabled"
              @on-open-change="quSel"
            >
              <Option
                v-for="(item, index) in libraryData"
                :key="index"
                :value="item.channelId"
                :label="item.channelName"
              >
              </Option>
            </Select>
          </div>
          <div class="nameSel" v-if="kuDisabled">
            <Input v-model="kuBack" maxlength="8" disabled />
          </div>

          <div class="nameSel" v-if="channelNameQie == 2">
            <Input
              v-model="librarySelVal1"
              placeholder="请填写渠道"
              maxlength="10"
            />
          </div>
        </div>
      </div>
      <div class="modalCon">
        <span>渠道状态：</span>
        <div class="modalConSel">
          <RadioGroup v-model="channelStatus" @on-change="channelStatusChoose">
            <Radio label="1" :disabled="kuDisabled">启用</Radio>
            <Radio label="2" :disabled="kuDisabled">禁用</Radio>
          </RadioGroup>
        </div>
      </div>

      <div slot="footer">
        <Button type="text" @click="modalCancel">取消</Button>
        <Button type="primary" :disabled="kuDisabled" @click="modalOk"
          >确定</Button
        >
      </div>
    </Modal>

    <Modal v-model="modal1" :closable="false" :mask-closable="false">
      <p class="modal1Text">该渠道已有关联的客户，不可删除。</p>
      <div slot="footer" class="modal1Footer">
        <Button type="primary" @click="modal1Ok">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { Message } from "view-design";
// import cityCode from '@/common/cityCode';

import {
  // getChannelList,
  getCityList,
  getCaseChannelCreate,
  // getChannelDisable,
  getCaseChannelUpdate,
  getCaseChannelDelete,
  getCaseChannelList,
  getChannelLibrary,
  getCaseList,
} from "@/api/configure.js";
import Button from "@/components/iview/components/button/button.vue";
export default {
  components: { Button },
  data() {
    return {
      create: false,
      userMess: JSON.parse(this.$tool.getStorage("userMess")),
      onresizeHeight: 0, //tabl高
      modal: false,
      modal1: false,
      channelId: "",

      caseName: "aa", //案场名字
      channelClassification: "", //渠道分类
      channelStatus: "1", //渠道状态
      channelNameQie: "1", //渠道切换

      channelVal: "",
      passagewayVal: "",

      provinceVal: "",
      cityVal: "",

      selProvinceVal: "",
      selCityVal: "",

      provinceValList: [],
      cityValList: [],
      cityValList1: [],

      passagewayList: [{ channelName: "", serialNo: 1, validate: "1" }],
      oldChannelsName: "",
      bjList: [], //老数据
      channels: [],
      newChannels: [],

      channelTypeData: [
        {
          id: 1,
          value: "线下投放",
        },
        {
          id: 2,
          value: "网络媒体",
        },
        {
          id: 3,
          value: "渠道带看",
        },
        {
          id: 4,
          value: "客户运营",
        },
         {
          id: 5,
          value: "其他",
        },
      ],
      channelTypeVal: "",
      libraryData: "", //渠道库
      librarySel: "", //渠道库选择包含名字和id
      librarySelVal: "", //渠道库选择
      librarySelVal1: "", //渠道库填写
      editChannelId: "",

      buildingId: "1",
      buildingAlias: "1",
      cityCode: "110100000",

      kuDisabled: false,
      kuDisabled1: false,

      caseList: "",
      searchChannelTypeVal: "", //搜索
      searchChannelName: "",

      //分页
      pageData: {
        total: 0,
        current: 1,
        rows: 10,
        pageSizeOpts: [10, 20, 30, 40, 50],
      },

      columns: [
        {
          title: "序号",
          type: "index",
          width: 100,
          align: "center",
        },
        {
          title: "渠道分类",
          key: "channelType",
          minWidth: 120,
          align: "center",
          render: (h, params) => {
            return h(
              "div",
              this.$formatter.switchName("channelType", params.row.channelType)
            );
          },
        },
        {
          title: "渠道名称",
          key: "channelName",
          minWidth: 120,
          align: "center",
        },
        {
          title: "操作时间",
          key: "updateTime",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", params.row.updateTime.substr(0, 16));
          },
        },
        {
          title: "操作人",
          key: "updateName",
          width: 200,
          align: "center",
        },
        {
          title: "状态",
          key: "validate",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", params.row.validate == 1 ? "启用" : "禁用");
          },
        },

        {
          title: "操作",
          key: "operation",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "a",
                {
                  on: {
                    click: (e) => {
                      e.stopPropagation();
                      this.editChannel(params.row);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "a",
                {
                  style: {
                    marginLeft: "10px",
                  },
                  on: {
                    click: (e) => {
                      e.stopPropagation();
                      this.delChannel(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],

      data: [],
    };
  },
  methods: {
    channelTypeChange(){
      this.librarySelVal=''
    },
    //搜索
    // searchChange() {
    //   this.reChannelList();
    // },
    buildingIdValChange(val) {
      console.log(val, "valav");
      this.$tool.setStorage({ caseBuildingId: JSON.stringify(val.value)});
      this.buildingId = val.value;
      this.buildingAlias = val.label;
      
      this.caseList.forEach((item) => {
        if (item.buildingId == val.value) {
          this.cityCode = item.cityCode;
        }
      });

      console.log(this.buildingId, this.buildingAlias, this.cityCode, "all");
      this.reChannelList();
    },
    reCaseList() {
      let params = {
        userId: this.userMess.userId,
      };

      getCaseList(params)
        .then((res) => {
          console.log("案场列表", res);
          this.caseList = res.list;
          this.buildingId = JSON.parse(this.$tool.getStorage('caseBuildingId'));
          if(res && res.list && res.list.length>0){
            res.list.forEach(item => {
              if(item.buildingId == this.buildingId){
                this.cityCode = item.cityCode;
                this.buildingAlias = item.buildingAlias;
              }
            });
            this.reChannelList();
          }
        })
        .catch((err) => {
          console.log("cath");
          this.$Message.error(err);
        });
    },
    modal1Ok() {
      this.modal1 = false;
    },
    librarySelChange(val) {
      this.librarySel = val;
    },
    channelStatusChoose(val) {
      console.log(val, "状态更改");
    },
    channelNameChange(val) {
      console.log(val, "渠道库，自定义");
      if (val == 1) {
        this.librarySelVal1 = "";
      } else {
        this.librarySelVal = "";
        this.librarySel = "";
      }
    },

    searchReset() {
      this.searchChannelTypeVal = "";
      this.searchChannelName = "";
      this.reChannelList();
    },
    searchBtn() {
      this.reChannelList();
    },

    //案场渠道列表
    reChannelList() {
      let params = {
        page: this.pageData.current,
        rows: this.pageData.rows,
        buildingId: this.buildingId,
        cityCode: this.cityCode,
        userId: this.userMess.userId,
      };

      getCaseChannelList(params)
        .then((res) => {
          console.log("案场渠道列表", res);
          this.data = res.list;
          this.pageData.total = parseInt(res.total);
        })
        .catch((err) => {
          console.log("cath");
          this.$Message.error(err);
        });
    },
    quSel(val){
      console.log(val,'渠道库下拉')
      if(val){
        if(this.channelTypeVal){
          this.reChannelLibrary();
        }else{
          this.$Message.warning('请先选择渠道分类。');
        }
        
      }
    },
    //案场渠道库
    reChannelLibrary() {
      let params = {
        buildingId: this.buildingId,
        cityCode: this.cityCode,
        channelType:this.channelTypeVal
      };

      getChannelLibrary(params)
        .then((res) => {
          console.log("案场渠道库", res);
          this.libraryData = res;
        })
        .catch((err) => {
          console.log("cath");
          this.$Message.error(err);
        });
    },

    modalCancel() {
      this.modal = false;
      this.channelStatus = "1";
      this.librarySelVal1 = "";
      this.librarySelVal = "";
      this.librarySel = "";
      this.channelNameQie = "1";
      this.channelTypeVal = "";
      this.libraryData = '';
    },

    modalOk() {
      console.log(this.channelVal, "this.channelVal");
      if (this.create) {
        console.log("我是新增");
        this.reChannelCreate();
      } else {
        console.log("我是编辑");
        this.reChannelUpdate();
      }
    },

    //新增案场渠道
    reChannelCreate() {
      if (!this.channelTypeVal) {
        this.$Message.warning("请选择渠道分类。");
      } else if (!this.librarySelVal && !this.librarySelVal1) {
        this.$Message.warning("请选择或填写渠道名称。");
      } else {
        let params = {
          buildingId: this.buildingId,
          cityCode: this.cityCode,
          channelType: this.channelTypeVal,
          createrId: this.userMess.userId,
          dataSource: this.channelNameQie, //1:渠道库 2:自定义
          validate: this.channelStatus, //是否有效(1:有效 2:无效)
        };
        if (this.channelNameQie == 1) {
          params.channelName = this.librarySel.label;
          params.baseChannelId = this.librarySel.value; //zt_base_channel表主键，当dataSource=1时必填
        } else {
          params.channelName = this.librarySelVal1;
        }
        getCaseChannelCreate(params)
          .then((res) => {
            console.log("渠道新增res1");
            this.$Message.success("渠道新增成功。");
            this.reChannelList();
            this.modalCancel();
          })
          .catch((err) => {
            console.log("catch1111");
            this.$Message.error(err);
          });
      }
    },
    huDisable(val) {
      console.log(val, "hu");
      val.validate == "1" ? (val.validate = "2") : (val.validate = "1");
      console.log(val, "hu1");
    },

    //编辑按钮
    editChannel(val) {
      this.create = false;
      this.modal = true;

      console.log(val, "bainji");
      this.channelTypeVal = Number(val.channelType);
      this.channelNameQie = val.dataSource;
      this.editChannelId = val.channelId;
      this.channelStatus = val.validate;

      if (val.dataSource == "1") {
        // this.librarySel.label = val.channelName;
        // this.librarySel.value = Number(val.channelId);
        this.librarySelVal = Number(val.channelId);
        this.kuBack = val.channelName;
        this.kuDisabled = true;
        console.log(this.kuDisabled, "this.kuDisabled");
      } else if (val.dataSource == "2") {
        this.librarySelVal1 = val.channelName;
        this.kuDisabled = false;
        this.kuDisabled1 = true;
      }
    },
    delChannel(val) {
      console.log(val, "要删除的行");
      this.$Modal.confirm({
        title: "提示",
        content: "<p> 是否删除？</p>",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          let params = {
            channelId: val.channelId,
            // channelName:val.channelName,
            createrId: this.userMess.userId,
          };
          getCaseChannelDelete(params)
            .then((res) => {
              this.reChannelList();
              this.$Message.success('删除成功。');
              console.log(res, "res");
            })
            .catch((err) => {
              console.log(err, "err");
              this.modal1 = true;
            });
        },
      });
    },

    isObjEqual(obj1, obj2) {
      var o1 = obj1 instanceof Object;
      var o2 = obj2 instanceof Object;
      if (!o1 || !o2) {
        /*  判断不是对象  */
        return obj1 === obj2;
      }
      if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
        //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
      }

      for (var attr in obj1) {
        var t1 = obj1[attr] instanceof Object;
        var t2 = obj2[attr] instanceof Object;
        if (t1 && t2) {
          return diff(obj1[attr], obj2[attr]);
        } else if (obj1[attr] !== obj2[attr]) {
          return false;
        }
      }
      return true;
    },
    //编辑渠道
    reChannelUpdate() {
      console.log("1");
      if (!this.channelTypeVal) {
        this.$Message.warning("请选择渠道分类。");
        console.log("2");
      } else if (!this.librarySelVal && !this.librarySelVal1) {
        this.$Message.warning("请选择或填写渠道名称。");
        console.log("3");
      } else {
        console.log("4");
        let params = {
          channelId: this.editChannelId,
          // channelType: this.channelTypeVal,
          createrId: this.userMess.userId,
          validate: this.channelStatus,
        };
        if (this.channelNameQie == 1) {
          params.channelName = this.librarySel.label;
        } else {
          params.channelName = this.librarySelVal1;
        }
        console.log("5");
        getCaseChannelUpdate(params)
          .then((res) => {
            console.log("6");
            this.$Message.success("渠道更新成功。");
            this.reChannelList();
            this.modalCancel();
          })
          .catch((err) => {
            console.log("catch1111");
            this.$Message.error(err);
          });
      }
    },

    addChannel() {
      this.modal = true;
      this.create = true;

      this.kuDisabled = false;
      this.kuDisabled1 = false;
      // this.reChannelLibrary();
    },

    // 分页 页码改变事件
    pageOnChangeFun(page) {
      this.pageData.current = page;
      this.reChannelList();
    },
    // 分页 每页条数改变事件
    pageOnPageSizeChangeFun(page) {
      this.pageData.rows = page;
      this.reChannelList();
    },
    // 初始化获取数据
    initData() {
      this.$nextTick(() => {
        this.onresizeHeight =
          window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100;
      });
    },
  },
  computed: {},
  created() {
    this.initData();
    this.reCaseList();
  },

  mounted() {
    window.onresize = () => {
      return (() => {
        setTimeout(() => {
          this.onresizeHeight =
            window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 150;
        }, 10);
      })();
    };
  },
};
</script>

<style lang="scss" scoped>
.channelConfig {
  .ivu-table-cell {
    padding: 0;
  }
  .ivu-table-cell-slot {
    & > .sp1:last-child {
      border: none;
    }
  }
  .title {
    padding: 8px 14px;
  }
  .allCustomersP {
    padding: 8px 14px;
  }
  .teamConfigBtn {
    margin: 10px 0;
    padding-left: 14px;
    display: flex;
    flex-direction: row;
    button {
      margin-right: 10px;
    }
  }
  .tab {
    margin: 10px 0;
    .sp1 {
      display: block;
      min-height: 48px;
      line-height: 48px;
      text-align: center;
      border-bottom: 1px #e8eaec solid;
    }
  }
  .firstColumns {
    padding-left: 20px;
  }
  .caoBtn {
    color: #2d8cf0;
    cursor: pointer;
    display: inline-block;
    padding: 0 5px;
  }
}
.modalCon {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
  & > span {
    flex: 2;
    text-align: right;
    line-height: 30px;
  }
  .modalConSel {
    flex: 9;
    .nameSel {
      margin-top: 10px;
    }
  }
}
.searchBox {
  flex: 1;
  display: flex;
  flex-direction: row;
  .caseSearch {
    display: flex;
    flex-direction: row;
  }
}
/* page */
.pagePublicStyle {
  // text-align: right;
  padding: 14px 10px;
  // margin-right: 30px;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}
.iconBox {
  margin-top: 6px;
}
.IconAdd {
  vertical-align: -4px;
  cursor: pointer;
}
.iconDisable {
  font-size: 12px;
  color: #2d8cf0;
  margin: 0 10px;
  cursor: pointer;
}
.modal1Text {
  padding: 20px 0;
  text-align: center;
}
.modal1Footer {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
